<?php
abstract class Backend_Controller_Crud_Vc extends Backend_Controller_Crud
{
	public function indexAction()
    {
    	parent::indexAction();

    	 $this->_resource->addInlineJs('
            var canPublish =  '.($this->_user->canPublish($this->_module)).';
        ');
    	        
        $media = Model_Medialib::getInstance();
        $media->includeScripts();
        
	    $this->_resource->addJs('/js/app/system/ContentWindow.js' , 1);
        $this->_resource->addJs('/js/app/system/RevisionPanel.js', 2);      
    } 
    /**
     * Read object action
     */
    public function loaddataAction()
    { 	
        $id = Request::post('id', 'integer', false);
        $version = Request::post('version','integer',0);
        
        if(!$id)
            Response::jsonSuccess(array());
        
        $vc = Model_Vc::getInstance();
        
        try{
            $obj = new Db_Object($this->_module, $id);
        }catch(Exception $e){
            Response::jsonError($this->_lang->CANT_EXEC);
        }
               
        if(!$version)     
             $version = $vc->getLastVersion($this->_module, $id);     
          
        if(!$version){
              $data = $obj->getData();
              $data['id'] = $obj->getId(); 
              Response::jsonSuccess($data);
        }
              
        $data = $vc->getData($this->_module, $id , $version);
          
        if(empty($data))
            Response::jsonError($this->_lang->CANT_LOAD);
            
        $data['id'] = $id; 
        $data['version'] = $version;
        $data['published'] = $obj->get('published');
        $data['staging_url'] = '';
        
        /*
         * Prepare  mltilink properties
         */      
        $fields = $obj->getFields();
        foreach($fields as $field){
            if($field=='id' || empty($data[$field]))
                continue;
            $linkObject = $obj->getLinkedObject($field);
            if($linkObject !== false)
                $data[$field] = array_values($this->_collectLinksData($data[$field] ,$linkObject));
        } 
        /*
         * Send response
         */
        Response::jsonSuccess($data);
    }
    
    /**
     * Edit action
     */
    public function editAction()
    {
        $id = Request::post('id', 'integer', false);
        if(!$id)
            $this->createAction();
        else 
            $this->updateAction();    
    }
    /**
     * Create object action
     */
    public function createAction()
    {   	
        $this->_checkCanEdit();
        self::insertObject(Backend_Controller::getPostedData($this->_module));
    }
    /**
     * Update object action
     */
    public function updateAction()
    { 
        $this->_checkCanEdit();
        self::updateObject(Backend_Controller::getPostedData($this->_module)); 
    }
    /**
     * Delete object action
     */
    public function deleteAction()
    {   
        $id = Request::post('id','integer', false);
            
        try{
        	$object = new Db_Object($this->_module , $id);
        }catch(Exception $e){
        	Response::jsonError($this->_lang->WRONG_REQUEST);
        }
    
         if(!$id)
            Response::jsonError($this->_lang->WRONG_REQUEST);
            
         if(!User_Admin::getInstance()->canDelete($this->_module))
            Response::jsonError($this->_lang->CANT_DELETE);
          
         if($this->_configMain->get('vc_clear_on_delete'))
             Model_Vc::getInstance()->removeItemVc($this->_module , $id);

         if(!$object->delete())
             Response::jsonError($this->_lang->CANT_EXEC);

         Response::jsonSuccess();
    }
    /**
     * Unpublish object
     */
    public function unpublishAction()
    {
        $id = Request::post('id','integer', false);
        
        if(!$id)
            Response::jsonError($this->_lang->WRONG_REQUEST);
        
        if(!User_Admin::getInstance()->canPublish($this->_module))
             Response::jsonError($this->_lang->CANT_PUBLISH);

        try{
            $object = new Db_Object($this->_module , $id);  
        }catch(Exception $e){
            Response::jsonError($this->_lang->CANT_EXEC);
        }
        
        self::unpublishObject($object);
      
    }
    /**
     * Publish changes
     */
    public function publishAction()
    {
        $id = Request::post('id','integer', false);
        $vers = Request::post('vers' , 'integer' , false);
        
        if(!$id || !$vers)
            Response::jsonError($this->_lang->WRONG_REQUEST);
        
        if(!User_Admin::getInstance()->canPublish($this->_module))
             Response::jsonError($this->_lang->CANT_PUBLISH);

        try{
            $object = new Db_Object($this->_module , $id);  
        }catch(Exception $e){
            Response::jsonError($this->_lang->CANT_EXEC);
        }        
        
        $vc= Model_Vc::getInstance();
        
        $data = $vc->getData($this->_module , $id , $vers); 
        
        if(isset($data['id']))
            unset($data['id']);
            
        if(empty($data))
            Response::jsonError($this->_lang->CANT_EXEC);
            
         foreach ($data as $k=>$v){
             if($object->fieldExists($k)){
                 if($object->getConfig()->isMultiLink($k) && !empty($v))
                     $v = array_keys($v);         
                 try{
                 	
                     $object->set($k , $v);
                 }catch (Exception $e){
                     Response::jsonError($this->_lang->VERSION_INCOPATIBLE);
                 }
             } 
         }   
             
        $object->set('published_version' , $vers);
        $object->set('published', true); 
              
        if(!$object->save(false))
            Response::jsonError($this->_lang->CANT_EXEC);
   
         $hl = Model_Historylog::getInstance();
         $hl->log(
                          User_Admin::getInstance()->id,
                          $object->getId(),
                          Model_Historylog::Publish ,
                          $object->getTable()
                 );   
        Response::jsonSuccess();
    } 
    /**
     * Insert Object into DB and VC
     * @param Db_Object $object
     * @return void
     */
    public static function insertObject( Db_Object $object)
    {
         $lang = Lang::getInstance();
        
         $object->author_id = User_Admin::getInstance()->id;
         $object->date_created  = date('Y-m-d H:i:s');
         
         if(!$recId = $object->save())
             Response::jsonError($lang->CANT_CREATE);
                                  
          $versNum = Model_Vc::getInstance()->newVersion($object);
          if(!$versNum)
                Response::jsonError($lang->CANT_CREATE);   
         
          Response::jsonSuccess(array('id'=>$recId,'version'=>$versNum ,'published'=>false));    
    }
    /**
 	 * Update object
     * @param Db_Object $object
     */
    public static function updateObject(Db_Object $object)
    {                 
        $lang = Lang::getInstance();
        
        $object->editor_id = User_Admin::getInstance()->id;
        $object->date_updated = date('Y-m-d H:i:s');
            
        Model_Historylog::getInstance()->log(
                          User_Admin::getInstance()->id,
                          $object->getId(),
                          Model_Historylog::NewVersion,
                          $object->getTable()
        ); 
      /*
       * Create new revision
       */
      $versNum = Model_Vc::getInstance()->newVersion($object);
              
      if(!$versNum )
            Response::jsonError($lang->CANT_CREATE);   
 
      try{     
             $oldObject = new Db_Object($object->getName(), $object->getId());                            
             /**
              * @todo Make sure that it's needed
              * Update object if not published
              */
             if(!$oldObject->get('published')){
                 $data =  $object->getData();
                 
                 foreach ($data as $k=>$v)
                     $oldObject->set($k , $v);                 
             }                     
             if(!$oldObject->save(false))
             	  Response::jsonError($lang->CANT_EXEC); 
             	  
      }catch (Exception $e){
      		Response::jsonError($lang->CANT_EXEC);
      }
      Response::jsonSuccess(array('id'=>$object->getId(),'version'=>$versNum,'published_version'=>$object->get('published_version'),'published'=>$object->get('published')));          
    }
    
    /**
     * Unpublish object
     * @param Db_Object $object
     */
    public static function unpublishObject(Db_Object $object)
    {
       if(!$object->get('published'))
            Response::jsonError($this->_lang->NOT_PUBLISHED);
              
       $object->set('published_version' , 0);
       $object->set('published', false); 
        
       if(!$object->save(false))
            Response::jsonError($this->_lang->CANT_EXEC);
            
       $hl = Model_Historylog::getInstance();
       $hl->log(
              User_Admin::getInstance()->id,
              $object->getId(),
              Model_Historylog::Unpublish ,
              $object->getTable()
        );   
        Response::jsonSuccess();  
    }
}